<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考试详情 - 老师端</title>
    <link rel="stylesheet" href="../css/common.css">
    <style>
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 15px;
            margin-bottom: 30px;
            text-align: center;
        }

        .page-title {
            font-size: 2.5em;
            margin: 0;
            font-weight: 300;
        }

        .page-subtitle {
            font-size: 1.1em;
            margin: 10px 0 0 0;
            opacity: 0.9;
        }

        .exam-info {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .exam-meta {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .meta-item {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 10px;
        }

        .meta-icon {
            font-size: 1.5em;
        }

        .meta-content {
            flex: 1;
        }

        .meta-label {
            font-size: 0.9em;
            color: #666;
            margin-bottom: 5px;
        }

        .meta-value {
            font-size: 1.1em;
            font-weight: 600;
            color: #333;
        }

        .tabs {
            display: flex;
            background: white;
            border-radius: 15px;
            margin-bottom: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .tab {
            flex: 1;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            background: #f8f9fa;
            border: none;
            font-size: 1em;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .tab.active {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }

        .tab-content {
            display: none;
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .tab-content.active {
            display: block;
        }

        .action-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 10px;
        }

        .btn-action {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1em;
            font-weight: 500;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }

        .btn-success {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
        }

        .btn-danger {
            background: linear-gradient(135deg, #dc3545, #c82333);
            color: white;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-action:hover {
            transform: translateY(-2px);
        }

        .search-box {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .search-input {
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 1em;
            width: 200px;
        }

        .search-select {
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 1em;
            width: 120px;
        }

        .btn-search {
            background: #667eea;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 1em;
        }

        .item-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .item-card {
            background: white;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            padding: 20px;
            transition: all 0.3s ease;
        }

        .item-card:hover {
            border-color: #667eea;
            transform: translateY(-2px);
        }

        .item-card.selected {
            border-color: #28a745;
            background: #f8fff8;
        }

        .item-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 15px;
        }

        .item-title {
            font-size: 1.1em;
            font-weight: 600;
            color: #333;
            margin: 0;
            flex: 1;
        }

        .item-meta {
            display: flex;
            flex-direction: column;
            gap: 5px;
            font-size: 0.9em;
            color: #666;
        }

        .item-content {
            color: #666;
            line-height: 1.5;
            margin-bottom: 15px;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .item-actions {
            display: flex;
            gap: 10px;
        }

        .btn-small {
            padding: 6px 12px;
            font-size: 0.8em;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }

        .empty-icon {
            font-size: 4em;
            margin-bottom: 20px;
            opacity: 0.5;
        }

        .empty-title {
            font-size: 1.5em;
            margin-bottom: 10px;
            color: #333;
        }

        .empty-description {
            font-size: 1em;
            line-height: 1.5;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .loading-spinner {
            display: inline-block;
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 15px;
            max-width: 600px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f0f0f0;
        }

        .modal-title {
            font-size: 1.5em;
            font-weight: 600;
            color: #333;
            margin: 0;
        }

        .btn-close {
            background: none;
            border: none;
            font-size: 1.5em;
            cursor: pointer;
            color: #666;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
        }

        .form-control {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 1em;
            transition: border-color 0.3s ease;
        }

        .form-control:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .form-textarea {
            min-height: 100px;
            resize: vertical;
        }

        .modal-footer {
            display: flex;
            gap: 15px;
            justify-content: flex-end;
            margin-top: 25px;
            padding-top: 20px;
            border-top: 2px solid #f0f0f0;
        }

        .btn-modal {
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1em;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .btn-cancel {
            background: #6c757d;
            color: white;
        }

        .btn-save {
            background: #667eea;
            color: white;
        }

        .btn-modal:hover {
            transform: translateY(-2px);
        }

        .selected-items {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }

        .selected-item {
            display: inline-block;
            background: #28a745;
            color: white;
            padding: 5px 12px;
            border-radius: 20px;
            margin: 5px;
            font-size: 0.9em;
        }

        .btn-remove {
            background: none;
            border: none;
            color: white;
            margin-left: 8px;
            cursor: pointer;
        }

        .sidebar-footer {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 20px;
            border-top: 1px solid var(--border-color);
        }

        .logout-btn {
            width: 100%;
            padding: 12px 16px;
            background: var(--error-color);
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .logout-btn:hover {
            background: #c82333;
            transform: translateY(-1px);
        }
    </style>
</head>
<body>
    <!-- 侧边栏 -->
    <div class="sidebar">
        <div class="sidebar-header">
            <h3>老师工作台</h3>
        </div>
        <ul class="sidebar-nav">
            <li class="nav-item">
                <a href="dashboard.html" class="nav-link">
                    <i>📊</i> 仪表盘
                </a>
            </li>
            <li class="nav-item">
                <a href="upload.html" class="nav-link">
                    <i>📤</i> 上传视频
                </a>
            </li>
            <li class="nav-item">
                <a href="videos.html" class="nav-link">
                    <i>🎥</i> 视频管理
                </a>
            </li>
            <li class="nav-item">
                <a href="exam-management.html" class="nav-link active">
                    <i>📝</i> 考试管理
                </a>
            </li>
            <li class="nav-item">
                <a href="question-management.html" class="nav-link">
                    <i>❓</i> 题目管理
                </a>
            </li>
            <li class="nav-item">
                <a href="profile.html" class="nav-link">
                    <i>👤</i> 个人资料
                </a>
            </li>
        </ul>
        
        <!-- 退出登录 -->
        <div class="sidebar-footer">
            <button class="logout-btn" onclick="UserManager.logout()">
                <i>🚪</i> 退出登录
            </button>
        </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <div class="content-wrapper">
            <div class="container">
        <div class="page-header">
            <h1 class="page-title" id="examTitle">考试详情</h1>
            <p class="page-subtitle" id="examDescription">配置考试题目和学生</p>
        </div>

        <!-- 考试信息 -->
        <div class="exam-info">
            <div class="exam-meta">
                <div class="meta-item">
                    <div class="meta-icon">📊</div>
                    <div class="meta-content">
                        <div class="meta-label">题目数量</div>
                        <div class="meta-value" id="questionCount">0 题</div>
                    </div>
                </div>
                <div class="meta-item">
                    <div class="meta-icon">⏱️</div>
                    <div class="meta-content">
                        <div class="meta-label">考试时长</div>
                        <div class="meta-value" id="timeLimit">0 分钟</div>
                    </div>
                </div>
                <div class="meta-item">
                    <div class="meta-icon">👥</div>
                    <div class="meta-content">
                        <div class="meta-label">参与学生</div>
                        <div class="meta-value" id="studentCount">0 人</div>
                    </div>
                </div>
                <div class="meta-item">
                    <div class="meta-icon">📅</div>
                    <div class="meta-content">
                        <div class="meta-label">创建时间</div>
                        <div class="meta-value" id="createdTime">未知</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 标签页 -->
        <div class="tabs">
            <button class="tab active" onclick="switchTab('questions')">题目管理</button>
            <button class="tab" onclick="switchTab('students')">学生管理</button>
            <button class="tab" onclick="switchTab('settings')">考试设置</button>
        </div>

        <!-- 题目管理标签页 -->
        <div id="questionsTab" class="tab-content active">
            <div class="action-bar">
                <button class="btn-action btn-primary" onclick="showAddQuestionModal()">
                    ➕ 添加题目
                </button>
                <div class="search-box">
                    <input type="text" class="search-input" id="questionSearchInput" placeholder="搜索题目...">
                    <select class="search-select" id="questionCategoryFilter">
                        <option value="">全部分类</option>
                    </select>
                    <select class="search-select" id="questionDifficultyFilter">
                        <option value="">全部难度</option>
                        <option value="1">简单</option>
                        <option value="2">较易</option>
                        <option value="3">中等</option>
                        <option value="4">较难</option>
                        <option value="5">困难</option>
                    </select>
                    <button class="btn-search" onclick="searchQuestions()">🔍 搜索</button>
                </div>
            </div>

            <!-- 已选题目 -->
            <div class="selected-items" id="selectedQuestions" style="display: none;">
                <h4>已选题目 (<span id="selectedQuestionCount">0</span>)</h4>
                <div id="selectedQuestionsList"></div>
            </div>

            <div id="questionLoadingState" class="loading">
                <div class="loading-spinner"></div>
                <p>正在加载题目列表...</p>
            </div>

            <div id="questionList" class="item-grid" style="display: none;">
                <!-- 题目列表将在这里动态生成 -->
            </div>

            <div id="questionEmptyState" class="empty-state" style="display: none;">
                <div class="empty-icon">❓</div>
                <h3 class="empty-title">暂无题目</h3>
                <p class="empty-description">没有找到符合条件的题目</p>
            </div>
        </div>

        <!-- 学生管理标签页 -->
        <div id="studentsTab" class="tab-content">
            <div class="action-bar">
                <button class="btn-action btn-primary" onclick="showAddStudentModal()">
                    ➕ 添加学生
                </button>
                <div class="search-box">
                    <input type="text" class="search-input" id="studentSearchInput" placeholder="搜索学生...">
                    <button class="btn-search" onclick="searchStudents()">🔍 搜索</button>
                </div>
            </div>

            <!-- 已选学生 -->
            <div class="selected-items" id="selectedStudents" style="display: none;">
                <h4>已选学生 (<span id="selectedStudentCount">0</span>)</h4>
                <div id="selectedStudentsList"></div>
            </div>

            <div id="studentLoadingState" class="loading">
                <div class="loading-spinner"></div>
                <p>正在加载学生列表...</p>
            </div>

            <div id="studentList" class="item-grid" style="display: none;">
                <!-- 学生列表将在这里动态生成 -->
            </div>

            <div id="studentEmptyState" class="empty-state" style="display: none;">
                <div class="empty-icon">👥</div>
                <h3 class="empty-title">暂无学生</h3>
                <p class="empty-description">没有找到符合条件的学生</p>
            </div>
        </div>

        <!-- 考试设置标签页 -->
        <div id="settingsTab" class="tab-content">
            <div class="action-bar">
                <button class="btn-action btn-success" onclick="saveExamSettings()">
                    💾 保存设置
                </button>
                <button class="btn-action btn-primary" onclick="publishExam()">
                    📢 发布考试
                </button>
            </div>

            <div class="exam-info">
                <h3>考试基本信息</h3>
                <div class="form-group">
                    <label class="form-label" for="examTitleInput">考试标题</label>
                    <input type="text" class="form-control" id="examTitleInput" required>
                </div>
                <div class="form-group">
                    <label class="form-label" for="examDescriptionInput">考试描述</label>
                    <textarea class="form-control form-textarea" id="examDescriptionInput" placeholder="请输入考试描述..."></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label" for="examTimeLimitInput">考试时长（分钟）</label>
                    <input type="number" class="form-control" id="examTimeLimitInput" min="5" max="180" value="60" required>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加题目模态框 -->
    <div class="modal" id="addQuestionModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">添加题目到考试</h3>
                <button class="btn-close" onclick="hideAddQuestionModal()">&times;</button>
            </div>
            <div id="addQuestionContent">
                <!-- 题目选择内容将在这里动态生成 -->
            </div>
        </div>
    </div>

    <!-- 添加学生模态框 -->
    <div class="modal" id="addStudentModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">添加学生到考试</h3>
                <button class="btn-close" onclick="hideAddStudentModal()">&times;</button>
            </div>
            <div id="addStudentContent">
                <!-- 学生选择内容将在这里动态生成 -->
            </div>
        </div>
    </div>
        </div>
    </div>

    <script src="../js/common.js"></script>
    <script>
        let currentExam = null;
        let allQuestions = [];
        let allStudents = [];
        let selectedQuestions = [];
        let selectedStudents = [];
        let currentTab = 'questions';

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAuth();
            loadExamData();
        });

        // 检查用户认证状态
        function checkAuth() {
            const user = UserManager.getCurrentUser();
            if (!user || user.role !== 1) {
                Message.error('请先登录老师账号');
                setTimeout(() => {
                    window.location.href = '../login.html';
                }, 1500);
                return;
            }
            document.getElementById('userInfo').textContent = `欢迎，${user.name}`;
        }

        // 加载考试数据
        function loadExamData() {
            const urlParams = new URLSearchParams(window.location.search);
            const examId = urlParams.get('examId');
            
            if (!examId) {
                Message.error('考试ID不存在');
                setTimeout(() => {
                    window.location.href = 'exam-management.html';
                }, 1500);
                return;
            }

            loadExamInfo(examId);
            loadExamQuestions(examId);
            loadExamStudents(examId);
            loadAllQuestions();
            loadAllStudents();
        }

        // 加载考试基本信息
        async function loadExamInfo(examId) {
            try {
                console.log('开始加载考试信息，examId:', examId);
                const response = await API.get(`/exam/teacher/detail/${examId}`);
                console.log('考试详情API响应:', response);
                
                if (response.success) {
                    currentExam = response.exam;
                    console.log('考试信息:', currentExam);
                    updateExamInfo();
                } else {
                    console.error('加载考试信息失败:', response.message);
                    Message.error(response.message || '加载考试信息失败');
                }
            } catch (error) {
                console.error('加载考试信息失败:', error);
                Message.error('加载考试信息失败，请稍后重试');
            }
        }

        // 更新考试信息显示
        function updateExamInfo() {
            if (!currentExam) return;

            document.getElementById('examTitle').textContent = currentExam.title;
            document.getElementById('examDescription').textContent = currentExam.description || '配置考试题目和学生';
            document.getElementById('questionCount').textContent = `${currentExam.totalQuestions || 0} 题`;
            document.getElementById('timeLimit').textContent = `${currentExam.timeLimit || 0} 分钟`;
            document.getElementById('studentCount').textContent = `${currentExam.studentCount || 0} 人`;
            document.getElementById('createdTime').textContent = formatDate(currentExam.createdTime);

            // 更新设置页面的表单
            document.getElementById('examTitleInput').value = currentExam.title || '';
            document.getElementById('examDescriptionInput').value = currentExam.description || '';
            document.getElementById('examTimeLimitInput').value = currentExam.timeLimit || 60;
        }

        // 加载考试题目
        async function loadExamQuestions(examId) {
            try {
                console.log('开始加载考试题目，examId:', examId);
                const response = await API.get(`/exam/teacher/${examId}/questions`);
                console.log('考试题目API响应:', response);
                
                if (response.success) {
                    selectedQuestions = response.questions || [];
                    console.log('考试题目数据:', selectedQuestions);
                    updateSelectedQuestions();
                } else {
                    console.error('加载考试题目失败:', response.message);
                    Message.error(response.message || '加载考试题目失败');
                }
            } catch (error) {
                console.error('加载考试题目失败:', error);
                Message.error('加载考试题目失败，请稍后重试');
            }
        }

        // 加载考试学生
        async function loadExamStudents(examId) {
            try {
                console.log('开始加载考试学生，examId:', examId);
                const response = await API.get(`/exam/teacher/${examId}/students`);
                console.log('考试学生API响应:', response);
                
                if (response.success) {
                    selectedStudents = response.students || [];
                    console.log('考试学生数据:', selectedStudents);
                    updateSelectedStudents();
                } else {
                    console.error('加载考试学生失败:', response.message);
                    Message.error(response.message || '加载考试学生失败');
                }
            } catch (error) {
                console.error('加载考试学生失败:', error);
                Message.error('加载考试学生失败，请稍后重试');
            }
        }

        // 加载所有题目
        async function loadAllQuestions() {
            try {
                const response = await API.get('/question/list');
                if (response.success) {
                    allQuestions = response.questions || [];
                    loadQuestionCategories();
                }
            } catch (error) {
                console.error('加载题目列表失败:', error);
            }
        }

        // 加载所有学生
        async function loadAllStudents() {
            try {
                const response = await API.get('/user/admin/list');
                if (response.success) {
                    allStudents = (response.users || []).filter(user => user.role === 2);
                }
            } catch (error) {
                console.error('加载学生列表失败:', error);
            }
        }

        // 加载题目分类
        async function loadQuestionCategories() {
            try {
                const response = await API.get('/question/categories');
                if (response.success) {
                    const categories = response.categories || [];
                    const categoryFilter = document.getElementById('questionCategoryFilter');
                    categoryFilter.innerHTML = '<option value="">全部分类</option>';
                    categories.forEach(category => {
                        categoryFilter.innerHTML += `<option value="${category}">${category}</option>`;
                    });
                }
            } catch (error) {
                console.error('加载分类列表失败:', error);
            }
        }

        // 切换标签页
        function switchTab(tabName) {
            // 更新标签页状态
            document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
            
            event.target.classList.add('active');
            document.getElementById(tabName + 'Tab').classList.add('active');
            
            currentTab = tabName;
            
            // 根据标签页加载相应数据
            if (tabName === 'questions') {
                renderQuestionList();
            } else if (tabName === 'students') {
                renderStudentList();
            }
        }

        // 渲染题目列表
        function renderQuestionList() {
            const questionList = document.getElementById('questionList');
            const loadingState = document.getElementById('questionLoadingState');
            const emptyState = document.getElementById('questionEmptyState');

            loadingState.style.display = 'none';

            if (allQuestions.length === 0) {
                showQuestionEmptyState();
                return;
            }

            questionList.innerHTML = allQuestions.map(question => {
                const isSelected = selectedQuestions.some(sq => sq.questionId === question.id);
                return `
                    <div class="item-card ${isSelected ? 'selected' : ''}" onclick="toggleQuestionSelection(${question.id})">
                        <div class="item-header">
                            <h4 class="item-title">题目 #${question.id}</h4>
                            <div class="item-meta">
                                <span>${question.category || '未分类'}</span>
                                <span>${question.difficultyText || '未设置'}</span>
                            </div>
                        </div>
                        <div class="item-content">${question.content}</div>
                        <div class="item-actions">
                            <button class="btn-action btn-small ${isSelected ? 'btn-danger' : 'btn-primary'}" 
                                    onclick="event.stopPropagation(); ${isSelected ? 'removeQuestionFromExam(' + question.id + ')' : 'addQuestionToExam(' + question.id + ')'}">
                                ${isSelected ? '移除' : '添加'}
                            </button>
                        </div>
                    </div>
                `;
            }).join('');

            questionList.style.display = 'grid';
        }

        // 渲染学生列表
        function renderStudentList() {
            const studentList = document.getElementById('studentList');
            const loadingState = document.getElementById('studentLoadingState');
            const emptyState = document.getElementById('studentEmptyState');

            loadingState.style.display = 'none';

            if (allStudents.length === 0) {
                showStudentEmptyState();
                return;
            }

            studentList.innerHTML = allStudents.map(student => {
                const isSelected = selectedStudents.some(ss => ss.studentId === student.id);
                return `
                    <div class="item-card ${isSelected ? 'selected' : ''}" onclick="toggleStudentSelection(${student.id})">
                        <div class="item-header">
                            <h4 class="item-title">${student.name}</h4>
                            <div class="item-meta">
                                <span>学号: ${student.username}</span>
                                <span>邮箱: ${student.email}</span>
                            </div>
                        </div>
                        <div class="item-content">学生信息</div>
                        <div class="item-actions">
                            <button class="btn-action btn-small ${isSelected ? 'btn-danger' : 'btn-primary'}" 
                                    onclick="event.stopPropagation(); ${isSelected ? 'removeStudentFromExam(' + student.id + ')' : 'addStudentToExam(' + student.id + ')'}">
                                ${isSelected ? '移除' : '添加'}
                            </button>
                        </div>
                    </div>
                `;
            }).join('');

            studentList.style.display = 'grid';
        }

        // 显示题目空状态
        function showQuestionEmptyState() {
            document.getElementById('questionLoadingState').style.display = 'none';
            document.getElementById('questionList').style.display = 'none';
            document.getElementById('questionEmptyState').style.display = 'block';
        }

        // 显示学生空状态
        function showStudentEmptyState() {
            document.getElementById('studentLoadingState').style.display = 'none';
            document.getElementById('studentList').style.display = 'none';
            document.getElementById('studentEmptyState').style.display = 'block';
        }

        // 切换题目选择状态
        function toggleQuestionSelection(questionId) {
            const isSelected = selectedQuestions.some(sq => sq.questionId === questionId);
            if (isSelected) {
                removeQuestionFromExam(questionId);
            } else {
                addQuestionToExam(questionId);
            }
        }

        // 切换学生选择状态
        function toggleStudentSelection(studentId) {
            const isSelected = selectedStudents.some(ss => ss.studentId === studentId);
            if (isSelected) {
                removeStudentFromExam(studentId);
            } else {
                addStudentToExam(studentId);
            }
        }

        // 添加题目到考试
        async function addQuestionToExam(questionId) {
            try {
                const response = await API.post(`/exam/${currentExam.id}/add-question/${questionId}`, {});
                if (response.success) {
                    Message.success('题目添加成功');
                    loadExamQuestions(currentExam.id);
                    renderQuestionList();
                } else {
                    Message.error(response.message || '添加题目失败');
                }
            } catch (error) {
                console.error('添加题目失败:', error);
                Message.error('添加题目失败，请稍后重试');
            }
        }

        // 从考试中移除题目
        async function removeQuestionFromExam(questionId) {
            try {
                const response = await API.post(`/exam/${currentExam.id}/remove-question/${questionId}`, {});
                if (response.success) {
                    Message.success('题目移除成功');
                    loadExamQuestions(currentExam.id);
                    renderQuestionList();
                } else {
                    Message.error(response.message || '移除题目失败');
                }
            } catch (error) {
                console.error('移除题目失败:', error);
                Message.error('移除题目失败，请稍后重试');
            }
        }

        // 添加学生到考试
        async function addStudentToExam(studentId) {
            try {
                const response = await API.post(`/exam/${currentExam.id}/add-student/${studentId}`, {});
                if (response.success) {
                    Message.success('学生添加成功');
                    loadExamStudents(currentExam.id);
                    renderStudentList();
                } else {
                    Message.error(response.message || '添加学生失败');
                }
            } catch (error) {
                console.error('添加学生失败:', error);
                Message.error('添加学生失败，请稍后重试');
            }
        }

        // 从考试中移除学生
        async function removeStudentFromExam(studentId) {
            try {
                const response = await API.post(`/exam/${currentExam.id}/remove-student/${studentId}`, {});
                if (response.success) {
                    Message.success('学生移除成功');
                    loadExamStudents(currentExam.id);
                    renderStudentList();
                } else {
                    Message.error(response.message || '移除学生失败');
                }
            } catch (error) {
                console.error('移除学生失败:', error);
                Message.error('移除学生失败，请稍后重试');
            }
        }

        // 更新已选题目显示
        function updateSelectedQuestions() {
            const selectedQuestionsDiv = document.getElementById('selectedQuestions');
            const selectedQuestionCount = document.getElementById('selectedQuestionCount');
            const selectedQuestionsList = document.getElementById('selectedQuestionsList');

            if (selectedQuestions.length === 0) {
                selectedQuestionsDiv.style.display = 'none';
                return;
            }

            selectedQuestionCount.textContent = selectedQuestions.length;
            selectedQuestionsList.innerHTML = selectedQuestions.map(sq => {
                const question = allQuestions.find(q => q.id === sq.questionId);
                return `
                    <span class="selected-item">
                        ${question ? question.content.substring(0, 20) + '...' : '题目 #' + sq.questionId}
                        <button class="btn-remove" onclick="removeQuestionFromExam(${sq.questionId})">&times;</button>
                    </span>
                `;
            }).join('');

            selectedQuestionsDiv.style.display = 'block';
        }

        // 更新已选学生显示
        function updateSelectedStudents() {
            const selectedStudentsDiv = document.getElementById('selectedStudents');
            const selectedStudentCount = document.getElementById('selectedStudentCount');
            const selectedStudentsList = document.getElementById('selectedStudentsList');

            if (selectedStudents.length === 0) {
                selectedStudentsDiv.style.display = 'none';
                return;
            }

            selectedStudentCount.textContent = selectedStudents.length;
            selectedStudentsList.innerHTML = selectedStudents.map(ss => {
                const student = allStudents.find(s => s.id === ss.studentId);
                return `
                    <span class="selected-item">
                        ${student ? student.name : '学生 #' + ss.studentId}
                        <button class="btn-remove" onclick="removeStudentFromExam(${ss.studentId})">&times;</button>
                    </span>
                `;
            }).join('');

            selectedStudentsDiv.style.display = 'block';
        }

        // 搜索题目
        async function searchQuestions() {
            const keyword = document.getElementById('questionSearchInput').value.trim();
            const category = document.getElementById('questionCategoryFilter').value;
            const difficulty = document.getElementById('questionDifficultyFilter').value;

            try {
                const params = new URLSearchParams();
                if (keyword) params.append('keyword', keyword);
                if (category) params.append('category', category);
                if (difficulty) params.append('difficulty', difficulty);

                const response = await API.get(`/question/search?${params.toString()}`);
                if (response.success) {
                    allQuestions = response.questions || [];
                    renderQuestionList();
                } else {
                    Message.error(response.message || '搜索失败');
                }
            } catch (error) {
                console.error('搜索题目失败:', error);
                Message.error('搜索失败，请稍后重试');
            }
        }

        // 搜索学生
        function searchStudents() {
            const keyword = document.getElementById('studentSearchInput').value.trim().toLowerCase();
            if (!keyword) {
                renderStudentList();
                return;
            }

            const filteredStudents = allStudents.filter(student => 
                student.name.toLowerCase().includes(keyword) ||
                student.username.toLowerCase().includes(keyword) ||
                student.email.toLowerCase().includes(keyword)
            );

            const originalStudents = allStudents;
            allStudents = filteredStudents;
            renderStudentList();
            allStudents = originalStudents;
        }

        // 保存考试设置
        async function saveExamSettings() {
            const title = document.getElementById('examTitleInput').value.trim();
            const description = document.getElementById('examDescriptionInput').value.trim();
            const timeLimit = parseInt(document.getElementById('examTimeLimitInput').value);

            if (!title) {
                Message.error('请输入考试标题');
                return;
            }

            try {
                const examData = {
                    title: title,
                    description: description,
                    timeLimit: timeLimit
                };

                const response = await API.put(`/exam/update/${currentExam.id}`, examData);
                if (response.success) {
                    Message.success('考试设置保存成功');
                    loadExamInfo(currentExam.id);
                } else {
                    Message.error(response.message || '保存失败');
                }
            } catch (error) {
                console.error('保存考试设置失败:', error);
                Message.error('保存失败，请稍后重试');
            }
        }

        // 发布考试
        async function publishExam() {
            if (!confirm('确定要发布这个考试吗？发布后学生就可以参加考试了。')) {
                return;
            }

            try {
                const response = await API.put(`/exam/publish/${currentExam.id}`, {});
                if (response.success) {
                    Message.success('考试发布成功');
                    loadExamInfo(currentExam.id);
                } else {
                    Message.error(response.message || '发布失败');
                }
            } catch (error) {
                console.error('发布考试失败:', error);
                Message.error('发布失败，请稍后重试');
            }
        }

        // 显示添加题目模态框
        function showAddQuestionModal() {
            // 这里可以实现批量添加题目的功能
            Message.info('请使用题目列表中的"添加"按钮来添加题目');
        }

        // 隐藏添加题目模态框
        function hideAddQuestionModal() {
            document.getElementById('addQuestionModal').style.display = 'none';
        }

        // 显示添加学生模态框
        function showAddStudentModal() {
            // 这里可以实现批量添加学生的功能
            Message.info('请使用学生列表中的"添加"按钮来添加学生');
        }

        // 隐藏添加学生模态框
        function hideAddStudentModal() {
            document.getElementById('addStudentModal').style.display = 'none';
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '未知';
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                UserManager.logout();
                window.location.href = '../login.html';
            }
        }
    </script>

    <!-- 侧边栏切换按钮 -->
    <button class="sidebar-toggle">☰</button>
</body>
</html>
